package cn.personal.study.services;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.mysql.cj.util.StringUtils;

import cn.personal.study.domain.User;
import cn.personal.study.domain.dto.request.UpdateUserRequestDTO;
import cn.personal.study.domain.dto.response.QueryUserResponseDTO;
import cn.personal.study.domain.mapper.UserRowMapper;


/**
 * 用户服务
 *
 * @author duliurui
 */
@Transactional(isolation= Isolation.REPEATABLE_READ ,rollbackFor = SQLException.class)
public class UserService {
    @Resource(name="user001")
    private User user1;
    @Resource(name="user002")
    private User user2;
    @Resource(name="user003")
    private User user3;
    private ScoreService scoreService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserService() {
    }

    public UserService(ScoreService scoreService) {
        this.scoreService = scoreService;
    }

    public void setScoreService(ScoreService scoreService) {
        this.scoreService = scoreService;
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId 用户id
     * @return 用户实体
     */
    public QueryUserResponseDTO getUser(String userId) {
        String sqlForSingle = "select id,name,age,remark from test_user where id=?";
        QueryUserResponseDTO user = jdbcTemplate.queryForObject(sqlForSingle, new Object[]{userId}, new UserRowMapper());

        return user;
    }
    public QueryUserResponseDTO findUser(String userId) {
        String sqlForSingle = "select id,name,age,remark from test_user where id=?";
        QueryUserResponseDTO user = jdbcTemplate.queryForObject(sqlForSingle, new Object[]{userId}, new UserRowMapper());

        return user;
    }

    public User viewUser(String userId) {
        if (user1 != null && user1.getId().equals(userId)) {
            return user1;
        }
        if (user2 != null && user2.getId().equals(userId)) {
            return user2;
        }
        return user3;
    }
    /**
     * 更新用户
     *
     * 实际开发中，应该读取数据库记录获取用户实体，此示例未连接数据库，仅模拟返回一个用户
     *
     * @return 用户实体
     */
    public Boolean updateUser(UpdateUserRequestDTO updateUserRequestDTO) throws SQLException {
        StringBuilder updateSql = new StringBuilder()
                .append("update test_user set name=?");
        List<Object> params = new ArrayList<>();
        params.add(updateUserRequestDTO.getName());
        if (updateUserRequestDTO.getAge() > 0) {
            updateSql.append(",age=?");
            params.add(updateUserRequestDTO.getAge());
        }
        if (StringUtils.isNullOrEmpty(updateUserRequestDTO.getRemark())) {
            updateSql.append(",remark=?");
            params.add(updateUserRequestDTO.getRemark());
        }
        updateSql.append(" where id=?");

        int operateResult = jdbcTemplate.update(updateSql.toString(), params.toArray());

        if(operateResult == 1) {
            throw new SQLException("测试脏读");
        }

        return operateResult == 1;
    }

    /**
     * 根据用户id获取用户实体
     *
     * 实际开发中，应该读取数据库记录获取用户实体，此示例未连接数据库，仅模拟返回一个用户
     *
     * @param userId 用户id
     * @return 用户实体
     */
    public User viewUserWithScore(String userId) {
        User user = viewUser(userId);
        scoreService.updateUserScore(user);
        return user;
    }

    public void printUsers(List<User> users) {
        for (User user : users) {
            System.out.println(user.toString());
        }
    }


}
